package web

import (
	"gitee.com/crack007/goose/gsutil"
	"github.com/gin-gonic/gin"
)

var RawJsonMiddleware = rawJsonMiddleware{}

type rawJsonMiddleware struct {
}

func (x *rawJsonMiddleware) Apply(iRoutes gin.IRoutes) {
	iRoutes.Use(x.Handle)
}

func (x *rawJsonMiddleware) Handle(ctx *gin.Context) {
	if ctx.Keys == nil {
		ctx.Keys = map[string]any{}
	}

	ctx.Next()
	dto := GetResponse(ctx)
	var resp string
	if v, ok := dto.(*ApiException); ok {
		resp = gsutil.JsonUtil.Marshal(v)
	} else {
		resp = gsutil.JsonUtil.Marshal(dto)
	}

	writer := &responseWriter{ResponseWriter: ctx.Writer, body: []byte{}}
	ctx.Writer = writer
	ctx.Header("Content-Type", "application/json")
	_, err := ctx.Writer.Write([]byte(resp))
	if err != nil {
		panic(err)
	}
}
